/**
 * 设备保养
 * author Forjune
 */
import React, { useEffect, useState, useRef, forwardRef } from 'react'
import { Button, Table, Tooltip, message } from 'antd'
import Paging from 'components/common/paging'
import ObjectList from 'components/common/ObjectList'
import router from 'umi/router'
import { connect } from 'dva'
import deviceUpkeepColumns from 'columns/deviceUpkeep'
import MessageModel from 'components/common/MessageModel'
import HeaderSearch from './components/headerSearch'
import { upkeepDel, upkeepStop, upkeepOpen } from 'dic/messageModel'
import { operUpkeep, stopOpenUpkeep } from 'service/actions/deviceUpkeep'
import KeepAlive from 'react-activation'
import './index.styl'
const HeaderSearchRef = forwardRef((props, ref) => (
  <HeaderSearch {...props} cRef={ref} />
));

function DeviceUpkeep({ dispatch, commonAction: { catchObj }, deviceUpkeep: { upkeep, plan, serachParams }, location }) {
  const { params = {}, pathname } = location
  const { status = '', today = '', isRefresh = false } = params
  const [size] = useState(10)
  const [current] = useState(upkeep.current || 1)
  const searchRef = useRef()
  useEffect(() => {
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          deviceUpkeep: [true, false]
        }
      }
    })
    return function cleanUp() {
      const nowPage = JSON.parse(localStorage.getItem('panes')).find(item => item.key === pathname)
      if (nowPage === undefined) {
        dispatch({
          type: 'deviceUpkeep/updateUpkeep',
          payload: {
            upkeep: {}
          }
        })
        dispatch({
          type: 'deviceUpkeep/updateSerachParams',
          payload: {
            serachParams: {}
          }
        })
      }
    }
  }, [dispatch, pathname])
  // 请求数据列表
  useEffect(() => {
    dispatch({
      type: 'deviceUpkeep/getUpkeepList',
      payload: {
        current,
        size,
        ...serachParams
      }
    })
  }, [dispatch, current, size, serachParams])
  useEffect(() => {
    if (isRefresh) {
      searchRef.current.resetFields()
    }
  }, [isRefresh])
  // 点击保养项目显示tooltip表格
  function handleShowTip(visible, id) {
    if (visible) {
      dispatch({
        type: 'deviceUpkeep/getUpkeepPlanList',
        payload: {
          id,
          current: 1,
          size: 5
        }
      })
    }
  }
  // 点击保养项目显示tooltip表格的分页
  function handleShowTipPage(page, id) {
    dispatch({
      type: 'deviceUpkeep/getUpkeepPlanList',
      payload: {
        id,
        current: page,
        size: 5
      }
    })
  }
  // 点击删除保养
  async function handleClick(id, method) {
    const data = await operUpkeep({
      id,
      method
    })
    if (data) {
      if (data.code === '000000') {
        message.success(data.mesg)
      } else {
        message.error(data.mesg)
      }
      dispatch({
        type: 'deviceUpkeep/updateSerachParams',
        payload: {
          serachParams: {
            current: 1
          }
        }
      })
      searchRef.current.resetFields()
    }
  }
  // 点击启用 停用
  async function handleStopOpen(id, status) {
    const data = await stopOpenUpkeep({
      id,
      status
    })
    if (data) {
      if (data.code === '000000') {
        message.success(data.mesg)
      } else {
        message.error(data.mesg)
      }
      dispatch({
        type: 'deviceUpkeep/updateSerachParams',
        payload: {
          serachParams: {
            current: 1
          }
        }
      })
      searchRef.current.resetFields()
    }
  }
  // 查看详情
  const handleDetail = (id) => {
    router.push({
      pathname: '/deviceUpkeep/detail',
      query: {
        id
      }
    })
  }
  deviceUpkeepColumns.list[0].render = (text, record, index) => {
    return <span>{(upkeep.current - 1) * 10 + (index + 1)}</span>
  }
  // 点击保养项目数字弹框的表格列表
  deviceUpkeepColumns.list[deviceUpkeepColumns.list.length - 3].render = (text, record) => (
    <div className='objectStyle'>
      <Tooltip
        placement="bottom"
        title={<ObjectList
          objectInfo={JSON.stringify(plan) !== '{}' ? plan : null}
          objectColumns={deviceUpkeepColumns.projectColumns}
          handleChangePage={(page) => handleShowTipPage(page, record.id)}
        />}
        trigger="hover"
        overlayStyle={{ background: '#fff', width: '20rem' }}
        onVisibleChange={(visible) => handleShowTip(visible, record.id)}
      >
        <span className='objectText'>{text}</span>
      </Tooltip>
    </div>
  )

  // 操作按钮
  deviceUpkeepColumns.list[deviceUpkeepColumns.list.length - 1].render = (text, record) => (
    <>
      {
        record.statusName === '待审批' && record.isApprovalUser ?
          <span className="td-blue" onClick={() => handleDetail(record.id)}>审批</span>
          :
          null
      }
      {
        record.statusName === '草稿' || record.statusName === '待审批' || record.statusName === '停用' || record.statusName === '审批失败' ?
          <MessageModel handleClick={() => handleClick(record.id, 'DELETE')} data={upkeepDel} />
          :
          null
      }
      {
        record.statusName === '草稿' || record.statusName === '待审批' || record.statusName === '停用' || record.statusName === '审批失败' ?
          <span className="td-blue" onClick={() => handleEdit(record.id)}>编辑</span>
          :
          null
      }
      {
        record.confirmedTaskCount && record.confirmedTaskCount > 0 ?
          <span className="td-blue" onClick={() => handleDetail(record.id)}>确认任务</span>
          :
          null
      }
      {
        record.statusName === '停用' ?
          <MessageModel handleClick={() => handleStopOpen(record.id, 3)} data={upkeepOpen} />
          :
          null
      }
      {
        record.statusName === '启用' ?
          <MessageModel handleClick={() => handleStopOpen(record.id, 4)} data={upkeepStop} />
          :
          null
      }
      <span className="td-blue" onClick={() => handleDetail(record.id)}>查看详情</span>
    </>
  )
  // 添加保养计划
  const handleAdd = () => {
    router.push('/deviceUpkeep/add')
  }
  // 编辑保养计划
  const handleEdit = (id) => {
    router.push({
      pathname: '/deviceUpkeep/edit',
      query: {
        id
      }
    })
  }
  return (
    <KeepAlive name='deviceUpkeep' when={catchObj.deviceUpkeep}>
      <div className='deviceUpkeep' id="deviceUpkeep">
        <HeaderSearchRef ref={searchRef} handleQuery={(v) => {
           dispatch({
            type: 'deviceUpkeep/updateSerachParams',
            payload: {
              serachParams: {
                ...v,
                current: 1
              }
            }
          })
        }} status={status} today={today} />

        <div className="deviceUpkeep-table">
          <Button className="blue-button btn_styls" onClick={handleAdd}>新建保养计划</Button>
          <Table
            columns={deviceUpkeepColumns.list}
            dataSource={upkeep && upkeep.records || []}
            pagination={false}
            className="self-table"
            bordered={true}
            rowKey={record => record.id}
          />
          <Paging
            total={upkeep && upkeep.total || 0}
            pageSize={10}
            handlePageChange={(c) => {
              dispatch({
                type: 'deviceUpkeep/updateSerachParams',
                payload: {
                  serachParams: {
                    ...serachParams,
                    current: c
                  }
                }
              })
            }}
            pageCount={upkeep && upkeep.current}
            pages={upkeep && upkeep.pages}
          ></Paging>
        </div>
      </div>
    </KeepAlive >
  )
}
export default connect(({ deviceUpkeep, commonAction }) => ({
  deviceUpkeep, commonAction
}))(DeviceUpkeep)
